const QuoteApi = require('../../../api/quote.js');
const UserApi = require('../../../api/user.js');
var {quotationColumns} = require('../../../utils/data.js');
const query = wx.createSelectorQuery();
const util = require('../../../utils/util.js')
const commonUtil = require('../../../utils/common.js')

Page({
  data: {
    currentMenu: null,
    currentSub: null,
    menuList: [],
    subList: [],
    ableView: true,
    tableInfo: {
      columns: [],
      data: []
    },
    modalContent: {
      title: null, content: null
    },
    currentQuoteGroupId: null,
    _globalData: null,
    dialogVisible: false,
  },
  
  onLoad(options){},

  onShow() {
    let that = this;
    setTimeout(()=>{
      that.initData()
    },200)
  },

  onUnload() {
    wx.removeStorageSync('currentMenuItem')
    wx.removeStorageSync('currentMenuItemList')
  },
  initData(){
    let _menuGroupList = wx.getStorageSync('menuGroupList');
    let _currentMenuItem = wx.getStorageSync('currentMenuItem');
    let _currentMenuItemList = wx.getStorageSync('currentMenuItemList');
    let token = wx.getStorageSync('token');
    let userService = wx.getStorageSync('userService');
    let _subListChilds = null;
    if (_currentMenuItemList[0] && _currentMenuItemList[0]['children']) {
      _subListChilds = _currentMenuItemList[0]['children'];
    }
    wx.setNavigationBarTitle({title: _currentMenuItem.itemName});

    this.setData({
      ['_globalData.token']: token,
      ['_globalData.userService']: userService,
      menuList: _currentMenuItemList,
      subList: _subListChilds ? _subListChilds : [],
      currentMenu: _currentMenuItemList[0],
      currentSub: _subListChilds && _subListChilds.length > 0 ? _subListChilds[0] : null,
      currentQuoteGroupId: _currentMenuItemList[0]['associated'] ? _currentMenuItemList[0]['quoteGroupId'] : 
      _subListChilds && _subListChilds.length > 0 ? _subListChilds[0]['associated'] ? _subListChilds[0]['quoteGroupId'] : null
       : null,
    })
    setTimeout(()=>{
      let _ableView = this.getAbleView();
      
      if (_ableView) {
        this.getGroupColumnListByQuoteGroupId(this.data.currentQuoteGroupId);
      }
      this.setData({
        ableView: _ableView
      })
    }, 200)

    if (token) {
      commonUtil.getUserServiceState();
      this.setData({['_globalData.userService']: wx.getStorageSync('userService')})
      if (userService) {
        this.getModalContent()
        if (['expire', 'expiring'].includes(userService.state)) {
          dialogVisible.value = true;
          this.setData({
            dialogVisible: true
          })
        }
      }
    }
  },
  // 判断内容是否可视
  getAbleView(){
    let currentMenuItem = wx.getStorageSync('currentMenuItem');
    if (this.data._globalData.token) {
      if (currentMenuItem['needPay']) {
          return this.data._globalData.userService && ['progress', 'expire', 'expiring'].includes(this.data._globalData.userService.state);
      } else {
          return true;
      }
    } else {
        return !currentMenuItem['needPay'];
    }
  },
  getModalContent(){
    let obj = {title: null, content: null};
    let userService = wx.getStorageSync('userService');
    if (userService) {
      if (userService.state === 'apply') {
        obj.title = '行情数据为收费服务';
        obj.content = '新客户可申请7天免费试用';
      } else if (userService.state === 'checking') {
        obj.title = '7天免费试用申请成功';
        obj.content = '审核通过后服务自动开通，请等待后台审核。';
      } else if (userService.state === 'start') {
        obj.title = '您订购的数据服务待生效';
        obj.content = `生效日期：${userService.openDate}~${userService.endDate}<br/>如有疑问，请联系客服。`;
      } else if (userService.state === 'expire') {
        obj.title = '您订购的数据服务将过期';
        obj.content = '为了不影响您的正常使用，请及时联系客服续约。';
      } else if (userService.state === 'expiring') {
        obj.title = '您订购的数据服务马上过期';
        obj.content = '为了不影响您的正常使用，请及时联系客服续约。';
      } else if (userService.state === 'expired') {
        obj.title = '您订购的数据服务已过期';
        obj.content = '行情数据服务：600元/年<br/>如需继续使用，请联系客服续约。';
      }
      this.setData({
        modalContent: obj
      })
    }
  },
  // 根据报价单id查询自定义表头
  getGroupColumnListByQuoteGroupId(_quoteGroupId){
    QuoteApi.getGroupColumnListByQuoteGroupId({quoteGroupId: _quoteGroupId}).then(res=>{
      if (res.retCode == "000000" && res.errCode == "000000") {
        if (res.data.length > 0) {
          let diyColumns = [];
          let selectedColumn = {label: "自选", prop: "collectTime"};
          diyColumns.push(selectedColumn);
          res.data.forEach(item=>{
            let column = {label: item.groupColumnName, prop: item.attributeValue};
            if (['lowestPrice','highestPrice','averagePrice','upsDowns','price','priceRange'].includes(item.attributeValue)) { column.align = 'right'; }
            diyColumns.push(column)
          })
          this.setData({
            ['tableInfo.columns']: diyColumns
          })
        } else {
          this.setData({
            ['tableInfo.columns']: quotationColumns
          })
        }
        this.getFrontQuoteGroup(_quoteGroupId)
      }
    })
  },
  // 获取报价单数据
  getFrontQuoteGroup(_quoteGroupId){
    QuoteApi.getFrontQuoteGroup({quoteGroupId: _quoteGroupId}).then(res=>{
      if (res.retCode == "000000" && res.errCode == "000000") {
        if (res.data && res.data.list) {
          res.data.list.forEach(item=>{
            if (item.quoteType == 'fixed') {
              item.price = item.averagePrice;
            }
            if (item.commodity) {
              item.commodityId = item.commodity.commodityId;
              item.commodityNo = item.commodity.commodityNo;
              item.commodityName = item.commodity.commodityName;
            }
            if (item.commodity && item.commodity.attributes.length>0) {
              item.commodity.attributes.forEach(sub=>{
                item[sub.attributeId] = sub.attributeValue;
              })
            }
            if (item.averagePrice) {item.averagePrice = Number(item.averagePrice)}
            if (item.highestPrice) {item.highestPrice = Number(item.highestPrice)}
            if (item.lowestPrice) {item.lowestPrice = Number(item.lowestPrice)}
            if (item.upsDowns) {item.upsDowns = Number(item.upsDowns)}
            if (item.quoteUnit) {item.quoteUnit = util.quoteUnitFilter(item.quoteUnit)}
            if (item.quoteDate) {item.quoteDate = util.formatDate(item.quoteDate, 'MM-DD')}
          })
          this.setData({
            ['tableInfo.data']: res.data.list
          })
        } else {
          this.setData({
            ['tableInfo.data']: []
          })
        }
      }
    })
  },
  // 添加或取消自选
  followQuote(_quoteId){
    QuoteApi.followQuote({quoteId: _quoteId}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        wx.showToast({
          icon: 'success',
          title: res.errMsg,
        })
        this.getGroupColumnListByQuoteGroupId(this.data.currentQuoteGroupId)
      } else {
        wx.showToast({
          icon: 'error',
          title: res.errMsg,
        })
      }
    })
  },
  // 菜单点击
  menuClick(e){
    let level = e.currentTarget.dataset.level;
    let currentItem = e.currentTarget.dataset.item;

    if (this.data.ableView) {
      query.select("#table-area").scrollLeft = 0;
      query.select("#level2").scrollLeft = 0;
    }
    if (level == 1) {
      this.setData({
        currentMenu: currentItem,
        subList: currentItem.children,
      })

      if (currentItem.children.length > 0) {
        this.setData({ currentSub: currentItem.children[0] })

        if (currentItem.children[0].quoteGroupId) {
          this.setData({currentQuoteGroupId: currentItem.children[0].quoteGroupId})
          if (this.data.ableView) {
            this.getGroupColumnListByQuoteGroupId(currentItem.children[0].quoteGroupId)
          }
        } else {
          this.setData({
            currentQuoteGroupId: null,
            ['tableInfo.data']: []
          })
        }
      } else {
        if (currentItem.quoteGroupId) {
          this.setData({currentQuoteGroupId: currentItem.quoteGroupId});
          if (this.data.ableView) {
            this.getGroupColumnListByQuoteGroupId(currentItem.quoteGroupId)
          }
        } else {
          this.setData({
            currentQuoteGroupId: null, 
            ['tableInfo.data']: []
          })
        }
      }
    } else if (level == 2) {
      this.setData({currentSub: currentItem});

      if (currentItem.quoteGroupId) {
        this.setData({currentQuoteGroupId: currentItem.quoteGroupId})
        if (this.data.ableView) {
          this.getGroupColumnListByQuoteGroupId(currentItem.quoteGroupId)
        }
      } else {
        this.setData({
          currentQuoteGroupId: null, 
          ['tableInfo.data']: []
        })
      }
    }
  },
  // 订阅操作
  toSave(e){
    let currentItem = e.currentTarget.dataset.item;
    if (this.data._globalData.token) {
      if (this.data._globalData.userService && ['progress', 'expire', 'expiring'].includes(this.data._globalData.userService.state)) {
        this.followQuote(currentItem.quoteId)
      } else {
        this.setData({dialogVisible: true})
        setTimeout(()=>{
          this.setData({dialogVisible: false})
        }, 3000)
      }
    } else {
      wx.showToast({
        icon: 'none',
        title: '请先登录',
      })
    }
  },
  // 登录后跳转回当前页
  redirectCurrent(){
    wx.removeStorageSync('userInfo')
    wx.removeStorageSync('token')
    wx.redirectTo({
      url: '/packageA/pages/login/index?redirect_uri=/packageA/pages/quotation/index&redirect_uri_type=link',
    })
  },
  // 登录操作
  toLogin(){
    this.redirectCurrent();
  },
  // 申请操作
  toApply(){
    UserApi.applyMemberServiceOrder().then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        wx.showToast({
          icon: 'success',
          title: "申请数据试用成功",
        })
        commonUtil.getUserServiceState();
      } else {
        wx.showToast({
          icon: 'error',
          title: res.errMsg,
        })
      }
    })
  }
})
